package com.cwt_taxi_xa.util;

import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.ConstantsState;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.model.GpsLocationInfo;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.timer.TimerCommon;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

public class GPSUtil {

	public static GPSUtil instance;

	// 获取本地application的对象
	public static GPSUtil getInstance() {
		if (instance == null) {
			instance = new GPSUtil();
		}
		return instance;
	}

	public Location locationInfo;

	public void init(){
		lManager = (LocationManager) MainApplication.getInstance().getSystemService(Context.LOCATION_SERVICE);
		// 监听状态
		lManager.addGpsStatusListener(listener);
		// 绑定监听，有4个参数
		// 参数1，设备：有GPS_PROVIDER和NETWORK_PROVIDER两种
		// 参数2，位置信息更新周期，单位毫秒
		// 参数3，位置变化最小距离：当位置距离变化超过此值时，将更新位置信息
		// 参数4，监听
		// 备注：参数2和3，如果参数3不为0，则以参数3为准；参数3为0，则通过时间来定时更新；两者为0，则随时刷新
		// 1秒更新一次，或最小位移变化超过1米更新一次；
		// 注意：此处更新准确度非常低，推荐在service里面启动一个Thread，在run中sleep(10000);然后执行handler.sendMessage(),更新位置
		try {
			lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
					locationListener);
		} catch (Exception e) {
			e.printStackTrace();
		}

		/**
		 *   Timer timer = new Timer();
		 12     TimerTask timerTask = new TimerTask() {
		 13         @Override
		 14         public void run() {
		 15             Message message = new Message();
		 16             message.what = 1;
		 17             handler.sendMessage(message);
		 18         }
		 19     };
		 20  主线程中调用：timer.schedule(timerTask,1000,500);//延时1s，每隔500毫秒执行一次run方法
		 */
		//定时器，检查gps是否定位
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					try {
						Thread.sleep(2000);
						if(System.currentTimeMillis()-locatime>2000){
							//未定位
							MyStatus.gps = false;
							ConstantsState.setStateValue(0, "1");
							if(MainApplication.topActivity!=null)
								MainApplication.topActivity.setStatus(3, false);
						}else{
							//已定位
							if(!MyStatus.gps){
								//未定位变成已定位，将校时即时调到直接发送
								TimerCommon.count_ddtime = 1000;
							}
							MyStatus.gps = true;
							ConstantsState.setStateValue(0, "0");
							if(MainApplication.topActivity!=null)
								MainApplication.topActivity.setStatus(3, true);
						}
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			}
		}).start();


		sendData();
	}


	public LocationManager lManager = null;
	public GpsLocationInfo gpslocationInfo = null;
	public GpsLocationInfo gpslocationInfo_last = null;

	/**
	 * 获取GPS位置信息
	 *
	 * @return
	 */
	public GpsLocationInfo getLocInfo() {
		if (gpslocationInfo == null) {
			gpslocationInfo = new GpsLocationInfo();
			gpslocationInfo.setTime(SPUtils.getParamLong(SPConstants.SPK_time,
					SPConstants.SPV_time));
			gpslocationInfo.setAltitude(SPUtils.getParamInteger(
					SPConstants.SPK_altitude, SPConstants.SPV_altitude));
			gpslocationInfo.setLat(SPUtils.getParamInteger(SPConstants.SPK_lat,
					SPConstants.SPV_lat));
			gpslocationInfo.setLng(SPUtils.getParamInteger(SPConstants.SPK_lng,
					SPConstants.SPV_lng));
			gpslocationInfo.setSpeed(SPUtils.getParamInteger(
					SPConstants.SPK_speed, SPConstants.SPV_speed));
			gpslocationInfo.setDirection(SPUtils.getParamInteger(
					SPConstants.SPK_direction, SPConstants.SPV_direction));
		}
		return gpslocationInfo;
	}

	long locatime;//上一次定位时间

	long time;
	int lng;
	int lat;
	int altitude;
	int speed;
	int direction;

	private boolean UPDATE_GPS_TIME = true;

	double juli = 0;

	public static double SinceLastUpload = 0;

	/**
	 * GPS获取位置监听
	 */
	private LocationListener locationListener = new LocationListener() {
		/**
		 * 位置信息变化时触发
		 */
		public void onLocationChanged(Location location) {

			locationInfo = location;
			locatime = System.currentTimeMillis();

			time = location.getTime();

			if(UPDATE_GPS_TIME && MyStatus.gps && time != 0){
				Calendar calendar =	Calendar.getInstance();
				calendar.setTimeInMillis(time);
				int year = calendar.get(Calendar.YEAR);
				if(year < 2018 || year >= 2070){
					return;
				}
				UPDATE_GPS_TIME = false;
				// 启动全程录音
				SerialPortService.handler.obtainMessage(1004).sendToTarget();
			}

			lng = (int) (location.getLongitude() * 1E6);
			lat = (int) (location.getLatitude() * 1E6);
			altitude = (int) location.getAltitude();
			speed = (int) (location.getSpeed() * 36f);
			direction = (int) location.getBearing();

//			sendData("[lng:"+lng+",lat"+lat+",speed"+speed+",time"+time+",direction"+direction+",altitude"+altitude+"]");
			GPSSTR = "[lng:"+lng+",lat:"+lat+",speed:"+(speed/10)+",time:"+time+",direction:"+direction+",altitude:"+altitude+"]";

			if (lng != 0 && lat != 0){
				SPUtils.setParam(SPConstants.SPK_lat,lat);
				SPUtils.setParam(SPConstants.SPK_lng,lng);
				SPUtils.setParam(SPConstants.SPK_time,time);
				SPUtils.setParam(SPConstants.SPK_speed,speed);
				SPUtils.setParam(SPConstants.SPK_altitude,altitude);
				SPUtils.setParam(SPConstants.SPK_direction,direction);
			}

//			System.out.println("时间：" + time);
//			System.out.println("经度：" + lng);
//			System.out.println("纬度：" + lat);
//			System.out.println("海拔：" + altitude);
//			System.out.println("方向：" + direction);

			if (gpslocationInfo == null) {
				gpslocationInfo = new GpsLocationInfo();
			}else{
				if (gpslocationInfo_last == null) {
					gpslocationInfo_last = new GpsLocationInfo();
				}else{
					//判断gps偏移
//					if(       Math.abs((((gpslocationInfo_last.getLng_f()-location.getLongitude())/((gpslocationInfo_last.getTime()-time)/100))* 1E10))>100*10000
//							||Math.abs((((gpslocationInfo_last.getLat_f()-location.getLatitude())/((gpslocationInfo_last.getTime()-time)/100))* 1E10))>100*10000
//							||speed==0
//					){
//						return;
//					}

//					saveTxt("speed:"+speed+"   lngdx:"+lngdx+"   latdx:"+latdx);

				}
				gpslocationInfo_last.setTime(gpslocationInfo.getTime());
				gpslocationInfo_last.setLng_f(gpslocationInfo.getLng_f());
				gpslocationInfo_last.setLat_f(gpslocationInfo.getLat_f());
			}
			gpslocationInfo.setTime(time);
			gpslocationInfo.setLng(lng);
			gpslocationInfo.setLat(lat);
			gpslocationInfo.setLng_f(location.getLongitude());
			gpslocationInfo.setLat_f(location.getLatitude());
			gpslocationInfo.setAltitude(altitude);
			gpslocationInfo.setSpeed(speed);
			gpslocationInfo.setDirection(direction);



			//用于测试GPS漂移情况
//			if(gpslocationInfo!=null&&gpslocationInfo_last!=null){
//				juli = DistanceUtil.getDistance(gpslocationInfo_last, gpslocationInfo);
//				if(juli>0&&juli<15){
//					saveTxt("-----------------0~15--------------------------->"+juli+"");
//				}
//				else if(juli>=15&&juli<33){
//					saveTxt("-----------------15~33--------------------------->"+juli+"");
//				}
//				else if(juli>=33){
//					saveTxt("----------------->33--------------------------->"+juli+"");
//				}
//				else{
//					saveTxt(juli+"");
//				}
//
//				if(lngMin==0||lngMin>lng){
//					lngMin = lng;
//				}
//				if(lngMax==0||lngMax<lng){
//					lngMax = lng;
//				}
//				if(latMin==0||latMin>lat){
//					latMin = lat;
//				}
//				if(latMax==0||latMax<lat){
//					latMax = lat;
//				}
//
//				saveTxt(lng+"");
//				saveTxt(lat+"");
//				saveTxt("lngMin:"+lngMin);
//				saveTxt("lngMax:"+lngMax);
//				saveTxt("latMin:"+latMin);
//				saveTxt("latMax:"+latMax);
//				saveTxt("最大距离:"+DistanceUtil.getDistance2(lngMin, latMin, lngMax, latMax));
//				saveTxt(sdf.format(new Date(time))+"");
//				saveTxt("");
//				saveTxt("");
//			}

		}

		File f;
		FileOutputStream fos;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int lngMin = 0;
		int lngMax = 0;
		int latMin = 0;
		int latMax = 0;
		public void saveTxt(String str){
			try {
				AppLog.e(str);
				if(f==null){
					f = new File("/mnt/sdcard/gpslog-"+new Date().getTime()+".txt");
					fos = new FileOutputStream(f);
				}
				fos.write((sdf.format(new Date())+"\n").getBytes());
				fos.write((str+"\n").getBytes());
				fos.flush();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		/**
		 * GPS状态变化时触发
		 */
		public void onStatusChanged(String provider, int status, Bundle extras) {
			switch (status) {
				// GPS状态为可见时
				case LocationProvider.AVAILABLE:
//				MyStatus.gps = true;
//				ConstantsState.setStateValue(0, "0");
//				AppLog.e("----------------AVAILABLE");
					break;
				// GPS状态为服务区外时
				case LocationProvider.OUT_OF_SERVICE:
//				MyStatus.gps = false;
//				ConstantsState.setStateValue(0, "1");
//				AppLog.e("----------------OUT_OF_SERVICE");
					break;
				// GPS状态为暂停服务时
				case LocationProvider.TEMPORARILY_UNAVAILABLE:
//				MyStatus.gps = false;
//				ConstantsState.setStateValue(0, "1");
//				AppLog.e("----------------TEMPORARILY_UNAVAILABLE");
					break;
			}

		}

		/**
		 * GPS开启时触发
		 */
		public void onProviderEnabled(String provider) {
			Location location = lManager.getLastKnownLocation(provider);
//			AppLog.e("----------------GPS开启");
		}

		/**
		 * GPS禁用时触发
		 */
		public void onProviderDisabled(String provider) {
//			AppLog.e("----------------GPS禁用");
//			MyStatus.gps = false;
//			ConstantsState.setStateValue(0, "1");
		}
	};

	/**
	 * 状态监听
	 */
	GpsStatus.Listener listener = new GpsStatus.Listener() {
		public void onGpsStatusChanged(int event) {
			switch (event) {
				// 第一次定位
				case GpsStatus.GPS_EVENT_FIRST_FIX:
//				AppLog.e("----------------====GPS已定位=========");
//				MyStatus.gps = true;
//				ConstantsState.setStateValue(0, "0");
					break;
				// 卫星状态改变
				case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
//				AppLog.e("GPS卫星状态改变");
					// 获取当前状态
					GpsStatus gpsStatus = lManager.getGpsStatus(null);
					// 获取卫星颗数的默认最大值
					int maxSatellites = gpsStatus.getMaxSatellites();
					// 创建一个迭代器保存所有卫星
					Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
							.iterator();
					int count = 0;
					while (iters.hasNext() && count <= maxSatellites) {
						GpsSatellite s = iters.next();
						count++;
					}
//				AppLog.e("搜索到：" + count + "颗卫星");
					break;
				// 定位启动
				case GpsStatus.GPS_EVENT_STARTED:
//				AppLog.e("----------------GPS定位启动");
//				MyStatus.gps = true;
//				ConstantsState.setStateValue(0, "0");
					break;
				// 定位结束
				case GpsStatus.GPS_EVENT_STOPPED:
//				AppLog.e("----------------GPS定位结束");
//				MyStatus.gps = false;
//				ConstantsState.setStateValue(0, "1");
					break;
			}
		};
	};









	DatagramSocket socket;
	InetAddress serverAddress;
	int port = 5008;
	Gson g;
	byte[] buffer;
	String GPSSTR;
	public void sendData(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
					}
					if(locatime!=0){
						if(System.currentTimeMillis()-locatime<2000){
							//AppLog.e("位置变动，发送到dvr1");
							//AppLog.e(GPSSTR);
							try {
								if(socket==null){
									socket = new  DatagramSocket (4568);
									serverAddress = InetAddress.getByName(SPConstants.SPV_dvrip_zg);
									g = new Gson();
									//AppLog.e("位置变动，发送到dvr2");
								}
								buffer = GPSSTR.getBytes();
//			buffer = g.toJson(info).getBytes();
								DatagramPacket  pg = new DatagramPacket (buffer , buffer.length , serverAddress , port);
								socket.send(pg);
								//AppLog.e("GPS2DVR："+new String(buffer));
								//AppLog.savelog("GPS2DVR："+new String(buffer));
								//AppLog.e("位置变动，发送到dvr3");
							} catch (Exception e) {
								//AppLog.e("位置变动，发送到dvr3 message:" + e.getMessage());
							}
						}
					}
				}
			}
		}).start();
	}







}
